from django import forms
from saas_main import models
from saas_main.forms import widgets


class ProjectForms(forms.ModelForm):
    class Meta:
        model = models.Project
        fields = ['project_title', 'project_color', 'project_desc']
        widgets = {
            "project_desc": forms.Textarea(attrs={}),
            "project_color": widgets.ColorRadioSelect(attrs={'class': 'color-radio'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # name 就是字段名字 field就是生成的input的标签对象
        for name, field in self.fields.items():
            # 这里会给每个标签对象属性重新赋值，不会保留原有属性，所以如果想保留原来属性需要进行判断(可以考虑update逻辑)
            if name in ['project_color']:
                continue
            if field.widget.attrs:
                field.widget.attrs['class'] = "form-control"
            else:
                field.widget.attrs = {"class": "form-control"}
            field.widget.attrs["placeholder"] = f"请输入{field.label}"


class WikiForm(forms.ModelForm):
    class Meta:
        model = models.Wiki
        fields = ['title', 'content', 'parent']

    def __init__(self, request, wiki_id, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # name 就是字段名字 field就是生成的input的标签对象
        for name, field in self.fields.items():
            if name == 'parent':
                data = [("", '根目录'), ]
                if wiki_id:
                    qs_list = models.Wiki.objects.filter(project=request.tracer.project.id).exclude(id=wiki_id) \
                        .values_list('id', 'title')
                else:
                    qs_list = models.Wiki.objects.filter(project=request.tracer.project.id).values_list('id', 'title')
                data.extend(qs_list)
                field.choices = data
            if field.widget.attrs:
                field.widget.attrs['class'] = "form-control"
            else:
                field.widget.attrs = {"class": "form-control"}
            field.widget.attrs["placeholder"] = f"请输入{field.label}"


class IssueForm(forms.ModelForm):
    class Meta:
        model = models.Issues
        exclude = ['project', 'creator', 'create_datetime', 'latest_update_datetime']
        widgets = {
            'assign': forms.Select(attrs={'class': 'selectpicker', 'data-live-search': 'true'}),
            'attention': forms.SelectMultiple(
                attrs={'class': 'selectpicker', 'data-live-search': 'true', 'data-actions-box': 'true'}),
            'issues_type': forms.Select(attrs={'class': 'selectpicker'}),
            'module': forms.Select(attrs={'class': 'selectpicker', 'data-live-search': 'true'}),
            'status': forms.Select(attrs={'class': 'selectpicker'}),
            'priority': widgets.ColorTextSelect(attrs={'class': 'selectpicker'}),
            'mode': forms.Select(attrs={'class': 'selectpicker'}),
            'parent': forms.Select(attrs={'class': 'selectpicker', 'data-live-search': 'true'}),
            'end_date': forms.DateInput(format='%Y-%m-%d'),
            'start_date': forms.DateInput(format='%Y-%m-%d')
        }

    def __init__(self, request, project, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # name 就是字段名字 field就是生成的input的标签对象
        for name, field in self.fields.items():
            # 这里会给每个标签对象属性重新赋值，不会保留原有属性，所以如果想保留原来属性需要进行判断(可以考虑update逻辑)
            if name == 'issues_type':
                self.filter_select_widget_data(field, models.IssuesType, 'id', 'title', project=project)
            elif name in ['attention', 'assign']:
                self.filter_select_widget_data(field, models.ProjectRelation, 'user__id', 'user__realname',
                                               project=project)
            elif name == 'module':
                self.filter_select_widget_data(field, models.Module, 'id', 'title', project=project)
            elif name == 'parent':
                self.filter_select_widget_data(field, models.Issues, 'id', 'subject', project=project)

            old_class = field.widget.attrs.get('class', '')
            field.widget.attrs['class'] = f"{old_class} form-control"
            field.widget.attrs["placeholder"] = f"请输入{field.label}"

    def filter_select_widget_data(self, field_obj, model, *args, **kwargs):
        if isinstance(field_obj.widget, forms.Select):
            data = []
            if not isinstance(field_obj.widget, forms.SelectMultiple):
                data = [('', f'请选择{field_obj.label}')]
            qs_list = model.objects.filter(**kwargs).values_list(*args)
            data.extend(qs_list)
            field_obj.choices = data


class InviteForm(forms.ModelForm):
    class Meta:
        model = models.ProjectInvite
        fields = ["period", "count"]
        widgets = {
            "period": forms.Select(attrs={'class': 'selectpicker'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            old_class = field.widget.attrs.get('class', '')
            field.widget.attrs['class'] = f"{old_class} form-control"
            field.widget.attrs["placeholder"] = f"请输入{field.label}"
